package dao.impl;

import dao.LikesDao;
import pojo.Likes;
import util.DataUtils;
import util.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class LikesDaoImpl implements LikesDao {
    private Connection conn = null;
    private ResultSet rs = null;
    private boolean flag = false;

    /**
     * 获取数据库某用户likes表数据
     *
     * @return
     */
    public ArrayList<Likes> likesList(Integer uid) throws SQLException, ClassNotFoundException {
        ArrayList<Likes> likesList = new ArrayList<>();
        conn = JdbcUtils.dbconn();
        rs = JdbcUtils.selectsql("select * from likes where uid='" + uid + "'");
//        while (true) {
//            if (!rs.next()) break;
//            Likes likes = new Likes();
//            likes.setNid(rs.getInt("nid"));
//            likes.setUid(rs.getInt("uid"));
//            likesList.add(likes);
//        }
        rs.last();
        int row = rs.getRow();
        rs.beforeFirst();
        do {
            row--;
            Likes likes = new Likes();
            likes = (Likes) DataUtils.dataEncapsulation(Class.forName("pojo.Likes"), rs);
            likesList.add(likes);
        } while (row > 0);
        JdbcUtils.closeconn(rs, null, conn);
        return likesList;
    }

    /**
     * 用户点赞笔记
     */

    public boolean UserLikeNote(Integer uid, Integer nid) throws SQLException {
        conn = JdbcUtils.dbconn();
        String sql = "insert into likes values('" + nid + "','" + uid + "')";
        String sql2 = "update biji set likes=likes+1 where nid='" + nid + "'";
        Integer j = JdbcUtils.addsql(sql2);
        Integer i = JdbcUtils.addsql(sql);
        if (i > 0 && j > 0) flag = true;
        JdbcUtils.closeconn(null, null, conn);
        return flag;
    }

    /**
     * 取消点赞
     *
     * @param uid
     * @param nid
     * @return
     */
    public boolean UserUnlikeNote(Integer uid, Integer nid) throws SQLException {
        conn = JdbcUtils.dbconn();
        String sql = "delete from likes where nid='" + nid + "' and uid='" + uid + "'";
        String sql2 = "update biji set likes=likes-1 where nid='" + nid + "'";
        Integer j = JdbcUtils.addsql(sql2);
        Integer i = JdbcUtils.addsql(sql);
        if (i > 0 && j > 0) flag = true;
        JdbcUtils.closeconn(null, null, conn);
        return flag;
    }

    /**
     * 查找某笔记点赞数
     *
     * @param nid
     * @return
     */
    public Integer noteLikes(Integer nid) throws SQLException {
        Integer number = 0;
        conn = JdbcUtils.dbconn();
        rs = JdbcUtils.selectsql("select likes from biji where nid='" + nid + "'");
        while (true) {
            if (!rs.next()) break;
            number = rs.getInt("likes");
        }
        JdbcUtils.closeconn(rs, null, conn);
        return number;

    }
}
